<template>
    <div id="people-work-type" class="w-h-100 pos-r flex-1 apply-container page-public-s"
        style="box-sizing: border-box;overflow:hidden;">
        <div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px;">
            <div class="search-s" style="box-sizing: border-box;">
                <el-card shadow="never" :body-style="{ paddingBottom: '0' }">
                    <el-form class="box-f" ref="queryForm" :inline="true">
                        <!-- <el-form-item label="选择搜索方式：">
                            <el-select v-model="searchVal" filterable class="m-2" placeholder="请选择搜索方式"
                                @change="searchChange" popper-class="set-select" :popper-append-to-body="false">
                                <el-option v-for="item in searchOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                        <el-form-item> -->
                            <!-- 员工姓名 -->
                            <!-- <template v-if="searchVal === '1'">
                                <el-input v-model="transferVal" placeholder="请输入员工姓名" />
                            </template> -->
                            <!-- 机构名称 -->
                            <!-- <template v-else-if="searchVal === '2'">
                                <el-select v-model="transferVal" filterable class="m-2" placeholder="机构名称"
                                    @change="acquireChange" value-key="id" popper-class="set-select"
                                    :popper-append-to-body="false">
                                    <el-option v-for="item in responsiblePle" :key="item.id" :label="item.name"
                                        :value="item.id" />
                                </el-select>
                            </template> -->
                            <!-- 工种类型 -->
                            <!-- <template v-else>
                                <el-select v-model="transferVal" filterable class="m-2" placeholder="工种类型"
                                    @change="acquireChange" value-key="n_Id" popper-class="set-select"
                                    :popper-append-to-body="false">
                                    <el-option v-for="item in recordPle" :key="item.n_Id" :label="item.v_WorkName"
                                        :value="item.n_Id" />
                                </el-select>
                            </template>
                        </el-form-item> -->
                        <el-form-item>
                            
                            <el-button v-if="$hasPer('PeopleWorkType1:add')" @click="nodeClick('')" icon="ele-Plus" type="primary"> 新增 </el-button>
                            <el-button v-if="$hasPer('PeopleWorkType7:excel')" @click="handleExport" icon="ele-Download"> 导出数据 </el-button>
                            <el-button v-if="$hasPer('PeopleWorkType2:download')" icon="ele-Download" @click="downClick">下载模板</el-button>
                            <el-upload v-if="$hasPer('PeopleWorkType3:import')" class="upload-demo" action="#" :auto-upload='false' ref="aModel"
                                :show-file-list="false" :on-change="(file: any) => { ExcelChange(file, getData) }"
                                :on-success="onSuccess" :limit="1">
                                <el-button icon="ele-Upload">导入Excel</el-button>
                            </el-upload>
                           
                        </el-form-item>
                    </el-form>
                </el-card>
            </div>

            <div style="box-sizing: border-box;" class="flex-1 pos-r">
                <div class="pos-a w-h-100" style="box-sizing: border-box;">
                    <el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px;">
                        <div style="" class="w-h-100 ver-flex">
                            <div class="flex-1 pos-r">
                                <div class="pos-a w-h-100">


                                    <el-table ref='excelRef' :data="list" class="w-h-100" style="width: 100%" border v-loading="loading"
                                        element-loading-background="rgba(0, 0, 0, 0.5)">
                                        <el-table-column type="index" label="序号" width="55" align="center"
                                            :index="indexMethod" />
                                            <el-table-column min-width="140" :show-overflow-tooltip="true" label="员工姓名"
                                            align="center">
                                            <el-table-column min-width="140" :show-overflow-tooltip="true" align="center">
                                            <template #header>
                                                <SearchModel typeId="v_EmpName" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
                                            </template>
                                            <template #default="scoped">
                                                <span v-if="scoped.row.v_EmpName">{{ scoped.row.v_EmpName }}</span>
                                                <span v-else>-</span>
                                            </template>
                                        </el-table-column>
                                        </el-table-column>
                                        <el-table-column min-width="140" :show-overflow-tooltip="true"
                                            label="工种名称" align="center" >
                                            <template #default="scope">
                                                    <span v-if="scope.row.v_WorkTypeName">{{ scope.row.v_WorkTypeName }}</span>
                                                    <span v-else> - </span>
                                                </template>
                                        </el-table-column>
                                        <el-table-column min-width="140" :show-overflow-tooltip="true"
                                            label="工种类别" align="center" prop="v_WorkTypeEmp" />
                                        <el-table-column  min-width="160" :show-overflow-tooltip="true"
                                            label="所属机构" align="center" >
                                            <template #default="scope">
                                                    <span v-if="scope.row.v_OrgName">{{ scope.row.v_OrgName }}</span>
                                                    <span v-else> - </span>
                                                </template>
                                        </el-table-column>
                                        <el-table-column prop="v_IssuingAuthority" min-width="140"
                                            :show-overflow-tooltip="true" label="发证机关" align="center" />
                                        <el-table-column prop="v_IssuingCertificate_No" min-width="140"
                                            :show-overflow-tooltip="true" label="证书编号" align="center" />
                                        <el-table-column prop="d_NextReview_Date" :formatter="formatDate" min-width="140"
                                            :show-overflow-tooltip="true" label="下次复查时间" align="center" />
                                            <el-table-column prop="i_NoticedDays" min-width="140"  :show-overflow-tooltip="true" label="提前提醒天数" align="center" />
                                        <el-table-column prop="createdTime" min-width="160" :show-overflow-tooltip="true"
                                            label="创建时间" align="center" />
                                        <el-table-column prop="createdUserName" min-width="160"
                                            :show-overflow-tooltip="true" label="创建者" align="center" />
                                        <el-table-column prop="updatedTime" min-width="160" :formatter="otherData"
                                            :show-overflow-tooltip="true" label="更新时间" align="center" />
                                        <el-table-column prop="updatedUserName" min-width="160" :formatter="otherData"
                                            :show-overflow-tooltip="true" label="更新者" align="center" />

                                        <el-table-column min-width="200" :show-overflow-tooltip="true" label="操作"
                                            align="center" fixed="right">
                                            <el-table-column min-width="200" :show-overflow-tooltip="true" align="center" fixed="right">
                                            <template #header>
                                                <el-button @click='searchClick' icon="ele-Search" type="primary" text> 查询 </el-button>
                            <el-button @click="resetClick" icon="ele-Refresh" text> 重置 </el-button>
                                            </template>
                                            <template #default="scope">
                                                <div class="operate-s">
                                                    <el-button v-if="$hasPer('PeopleWorkType4:edit')" @click="nodeClick(scope.row)" class="icon-e" icon="ele-Edit"
                                                        size="small" text type="primary"> 编辑 </el-button>
                                                        <el-button v-if="$hasPer('PeopleWorkType5:create')" size="small" @click="documentClick(scope.row)" text
                                                        type="primary"> 附件管理 </el-button>
                                                    <el-button v-if="$hasPer('PeopleWorkType6:delete')" @click="deleteHandle(scope.row.n_Id, getData)"
                                                        class="icon-e" icon="ele-Delete" size="small" text type="danger"> 删除
                                                    </el-button>
                                                    
                                                </div>
                                            </template>
                                        </el-table-column>
                                        </el-table-column>
                                    </el-table>
                                </div>
                            </div>
                            <div style="height: 30px;margin-top: 20px;" class="hr-flex-start">
                                <el-pagination v-model:currentPage="pageNo" v-model:page-size="pageSize" :total="totalRows"
                                    :page-sizes="[10, 20, 50, 100]" small background @size-change="handleSizeChange"
                                    @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper"
                                    class="w-h-100" />
                            </div>
                        </div>
                    </el-card>
                </div>
            </div>
        </div>
        <add-edit-people-work-type :repairInfo="repairInfo" :isUseDialog="isUseDialog" @updateData="getData"
            @cancelUseClick="cancelUseClick" @controlUseClick="controlUseClick" />
        <uploadFile isAccept="" :fileInfo="fileInfo" :isUseDialog="fileDialog" @cancelFileClick="cancelFileClick"
            @controlFileClick="controlFileClick" @updateData="getData" />
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, Ref, onMounted, reactive, toRaw } from 'vue';
import getTableData from '/@/utils/getTableData';
import { EmpWorkTypeQueryPageList, sysOrgList, WorkTypeGetList, EmpWorkTypeDelete, UploadBatchImportDataV3 } from '/@/api/centerControl/oms';
import AddEditPeopleWorkType from './component/oms/add-edit-people-work-type.vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import uploadFile from '/@/views/oms/component/reviseUploadFile.vue'
import SearchModel from '/@/views/oms/component/search-model.vue';
import { exportToExcel } from '/@/utils/exportToExcel';
export default defineComponent({
    name: 'people-work-type',
    components: {
        AddEditPeopleWorkType,
        uploadFile,
        SearchModel
    },
    setup(props) {
        // const { proxy } = useCurrentInstance();
        // const $t = proxy.$t;

        const isUseDialog = ref() // 新增/编辑弹出框隐藏/显示
        const repairInfo = ref() // 传递子组件数据
        const searchVal = ref('1')
        const transferVal = ref() // 需要查询的值
        const projectNam = ref() // 项目名称数据
        const responsiblePle = ref() // 组织机构
        const recordPle = ref() // 演习记录人数据
        let searchName = '1'
        let searchObj: any = reactive({})
        const aModel: Ref = ref(null)
        const pathData = ref(import.meta.env.VITE_API_URL + '/') // 获取地址

        /*** 截取日期格式方法 */
        const otherData = (row: any, column: any) => {
            // 获取单元格数据
            let data = row[column.property]
            if (data == null) {
                return '-'
            } else {
                return data
            }
        }

        /*** 截取日期格式方法 */
        const formatDate = (row: any, column: any) => {
            // 获取单元格数据
            let data = row[column.property]
            if (data == null) {
                return null
            }
            let dt = new Date(data)
            let month = (dt.getMonth() + 1) < 10 ? '0' + (dt.getMonth() + 1) : (dt.getMonth() + 1)
            let date = dt.getDate() < 10 ? '0' + dt.getDate() : dt.getDate()
            return dt.getFullYear() + '-' + month + '-' + date
        }

        /*** resetFun */
        const resetFun = () => {
            let newObj = Object.keys(searchObj)
            if (newObj.length !== 0) {
                newObj.map((i: any) => {
                    searchObj[i] = ''
                })
            }
        }

        /*** GetInfo 获取组件信息 */
        const GetInfo = async () => {
            let param = { isParentTree: true, type: 2 }
            let res: any = await sysOrgList(param)
            if (res.success) {
                responsiblePle.value = res.data
            }
            let workRes: any = await WorkTypeGetList({})
            if (workRes.success) {
                recordPle.value = workRes.data.map((item: any) => {
                    return {
                        label: item.v_WorkName,
                        value: item.id
                    }
                })
            }
        }

        /*** 搜索类型选择事件 searchChange */
        const searchChange = (val: any) => {
            searchName = val
            transferVal.value = ''
        }

        /*** acquireChange 搜索下拉框选择的数据 ---- 传给接口数据 */
        const acquireChange = (val: any) => {
            console.log(val)
        }

        /*** searchClick 查询按钮 */
        const searchClick = () => {
            // resetFun()
            // if (searchName === '1') { searchObj.v_EmpName = transferVal.value }
            // if (searchName === '2') { searchObj.v_OrgName = transferVal.value }
            // if (searchName === '3') { searchObj.n_WorkType_Id = transferVal.value }
            let newObj = Object.keys(searInfo.value);
			if (newObj.length !== 0) {
				newObj.map((i: any) => {
					searchObj[i] = searInfo.value[i];
				});
			}
        }

        /*** resetClick 重置按钮 */
        const resetClick = () => {
            searInfo.value = {};
			let newObj = Object.keys(searchObj);
			if (newObj.length !== 0) {
				newObj.map((i: any) => {
					searchObj[i] = '';
					// console.log(i);
				});
			}
			initInfoFun();
        }

        /*** nodeClick 新增/编辑点击事件 */
        const nodeClick = (val: string | object) => {
            val !== '' ? repairInfo.value = JSON.stringify(toRaw(val)) : repairInfo.value = ''
            isUseDialog.value = true
        }
        /*** deleteHandle 删除数据事件 */
        const deleteHandle = async (val: String | Number, updateFun: Function) => {
            ElMessageBox.confirm('请确定是否删除此条数据', '警告',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(async () => {
                    let param = { n_Id: val }
                    try {
                        let res: any = await EmpWorkTypeDelete(param)
                        if (res.success) {
                            updateFun()
                        }
                    } catch (err) { return }
                })
                .catch(() => {
                    ElMessage({
                        type: 'info',
                        message: '已取消',
                    })
                })
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            isUseDialog.value = false
        }

        /*** controlUseClick 提交事件 */
        const controlUseClick = () => {
            isUseDialog.value = false
        }

        /*** downClick 下载模板 */
        const downClick = () => {
            // window.location.href = 'www.baidu.com' // 覆盖当前页
            window.open(toRaw(pathData.value) + 'Upload/SMS/Batch/EmpWorkType.xlsx', '_blank') // 打开新页面
        }

        /*** ExcelChange 导入Excel */
        const ExcelChange = (item: any, updateFun: Function) => {
            let reader = new FileReader()
            let arr:any=[]
            reader.readAsDataURL(item.raw)
            reader.onload = (e: any) => {
                let base64String = e.target.result;
                let param: any = new Object()
                param.ModelType = 'EmpWorkType'
                param.FileContent = base64String
                arr.push(item.raw)
                uploadFun(arr, updateFun)
            }
        }
        /*** uploadFun 批量导入数据接口 */
        const uploadFun = async (arr: any, updateFun: Function) => {
            aModel.value.clearFiles()
            let res: any = await UploadBatchImportDataV3({file:arr})
            if (res.success) {
                updateFun()
                ElMessage.success('导入成功')
            }
        }

        /*** onSuccess 文件上传成功时的钩子函数 */
        const onSuccess = (item: any) => {
            console.log(item, 'item')
        }

        onMounted(() => {
            GetInfo()
        })

        /*** 附件管理 */
        const fileInfo = ref();
        const fileDialog = ref(false);
        /*** cancelFileClick 文件上传取消事件 */
        const cancelFileClick = () => {
            fileDialog.value = false;
        };

        /*** controlFileClick 文件上传提交事件 */
        const controlFileClick = () => {
            fileDialog.value = false;
        }

        /*** documentClick 文档上传事件 */
        const documentClick = (val: any) => {
            console.log(val, 'val')
            val.sourceType = 11;
            val.l_FileId = val.n_Id;
            val.sourceId = val.n_Id;
            val.titleCon = '附件上传';
            fileInfo.value = JSON.stringify(val);
            fileDialog.value = true;
        }
        const recordPle1 = [
			{ label: '一般作业人员', value: 2 },
			{ label: '特殊作业人员', value: 1 },
		];


        /*** 初始化数据 */
		const basicsInfo: any = ref([]);
		const initInfoFun = () => {
			basicsInfo.value = [
				{
					typeId: 'v_WorkTypeEmp', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
					typeNam: '', // 输入类型(number,text等) --- 选填
					searchVal: 'N_WorkType_Id', // 查询字段 --- 必填
					defaultVal: '', // 字段默认值 --- 选填
					placeholder: '工种类型', // placeholder数据
					defaultProp: recordPle1, // 下拉框中使用，除下拉框外其它情况为空 --- 选填
					eventType: '', // 事件类型（如burl/change等） --- 选填
					defaultEvent: '', // 事件名称 --- 选填
				},
				{
					typeId: 'v_EmpName', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
					typeNam: '', // 输入类型(number,text等) --- 选填
					searchVal: 'v_EmpName', // 查询字段 --- 必填
					defaultVal: '', // 字段默认值 --- 选填
					placeholder: '员工姓名', // placeholder数据
					defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
					eventType: '', // 事件类型（如burl/change等） --- 选填
					defaultEvent: '', // 事件名称 --- 选填
				},
			];
		};

		const searInfo: any = ref();
		const searchHandel = (val: any) => {
			searInfo.value = val;
		};

        onMounted(async () => {
			await initInfoFun();
		});

          /*** ================================= 导出数据函数操作 ================================= */
		  const excelRef: any = ref(null);
        const handleExport = () => {
            if(excelRef.value){
                if(excelRef.value.data.length !== 0){
                    let tableExcel: any = [];
                    let tableArr = excelRef.value.data;
                    tableArr.map((item: any) => {
                        let tableObj: any = {};
                        tableObj['员工姓名'] = item.v_EmpName ? item.v_EmpName : '-';
                        tableObj['工种名称'] = item.v_WorkTypeName ? item.v_WorkTypeName : '-';
						tableObj['工种类别'] = item.v_WorkTypeEmp ? item.v_WorkTypeEmp : '-';
                        tableObj['所属机构'] = item.v_OrgName ? item.v_OrgName : '-';
                        tableObj['发证机关'] = item.v_IssuingAuthority ? item.v_IssuingAuthority : '-';
                        tableObj['证书编号'] = item.v_IssuingCertificate_No ? item.v_IssuingCertificate_No : '-';
                        tableObj['提前提醒天数'] = item.i_NoticedDays ? item.i_NoticedDays : '-';
                        
						tableObj['下次复查时间'] = item.d_NextReview_Date ? item.d_NextReview_Date : '-';

                        tableObj['创建人'] = item.createdUserName ? item.createdUserName : '-';
                        tableObj['创建时间'] = item.createdTime ? item.createdTime : '-';
                        tableObj['更新人'] = item.updatedUserName ? item.updatedUserName : '-';
                        tableObj['更新时间'] = item.updatedTime ? item.updatedTime : '-';
                        tableExcel.push(tableObj);
                    });
                    exportToExcel(tableExcel,'工种证书.xlsx');
                }else{
                    ElMessage({
                        type: 'error',
                        message: '暂无数据导出',
                    })
                }
            }
        }

        return {
            ...getTableData(EmpWorkTypeQueryPageList, {}, searchObj),
            isUseDialog,
            cancelUseClick,
            controlUseClick,
            nodeClick,
            repairInfo,
            deleteHandle,
            resetClick,
            searchClick,
            downClick, // 下载模板
            ExcelChange, // 导入Excel
            onSuccess,
            aModel,
            recordPle1,
            searchOptions: [{
                value: '1',
                label: '员工姓名'
            }, {
                value: '2',
                label: '机构名称'
            }, {
                value: '3',
                label: '工种类型'
            }], // 搜索方式
            searchVal,
            searchChange,
            transferVal,
            acquireChange,
            projectNam, // 工种名称数据
            responsiblePle, // 工种编号数据
            recordPle, // 工种类型数据
            formatDate,
            otherData,
            pathData,
            documentClick, controlFileClick, cancelFileClick,fileDialog,fileInfo,
            searchHandel,
            basicsInfo,handleExport,excelRef
        }
    },
})
</script>
<style lang="scss"> @import './style/public.scss';
</style>
<style scoped lang="scss">
#people-work-type {
    .box-f {
        :deep(.el-form-item__label) {
            padding: 0;
        }
    }

    :deep(.el-card__body) {
        height: 100%;
    }

    :deep(.el-card) {
        border: none !important;
    }

    .upload-demo {
        margin-left: 12px;
        margin-top: 2px;
    }

    ul {

        list-style: none;

        li {
            cursor: pointer;

            &:hover {
                color: red;
            }
        }
    }

    .icon-e {
        :deep(.el-icon) {
            margin-right: 0px !important;
        }
    }
}
</style>